package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachPlanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

@Service
public class TeachPlanServiceImpl implements TeachPlanService {

    @Autowired
    private TeachplanMapper teachplanMapper ;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper ;

    @Override
    public List<TeachplanDto> findTeachPlanTree(Long courseId) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    @Override
    public void saveTeachPlan(SaveTeachplanDto saveTeachplanDto) {
        Long teachPlanId = saveTeachplanDto.getId();
        if(StringUtils.isEmpty(teachPlanId)){
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);

            Long parentid = saveTeachplanDto.getParentid();
            Long courseId = saveTeachplanDto.getCourseId();

            int count = getTeachPalnCount(parentid, courseId);
            teachplan.setOrderby(count);
            teachplan.setCreateDate(LocalDateTime.now());
            teachplan.setChangeDate(LocalDateTime.now());
            teachplanMapper.insert(teachplan) ;
        }else{
            Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplan.setChangeDate(LocalDateTime.now());
            teachplanMapper.updateById(teachplan);
        }

    }
    //删除教学计划
    @Transactional
    @Override
    public void deleteTeachPlan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if(!StringUtils.isEmpty(teachplan)){
            Long parentId = teachplan.getParentid();
            if(parentId==0){
//                表示章节删除
                LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper=queryWrapper.eq(Teachplan::getParentid,id);
                Integer integer = teachplanMapper.selectCount(queryWrapper);
                if(integer>0){
//                    有小章节
                    XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
                }else{
//                    删除章节
                    teachplanMapper.deleteById(id);
                }
            }else{
//                小节删除

                LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TeachplanMedia::getTeachplanId,id);
                TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(queryWrapper);
                if(StringUtils.isEmpty(teachplanMedia)){//判断是否有视频
                    teachplanMapper.deleteById(id);
                }else{
                    teachplanMediaMapper.deleteById(teachplanMedia.getId());
                    teachplanMapper.deleteById(id);
                }
            }
        }else{
            XueChengPlusException.cast("课程计划不存在删除失败");
        }

    }

    @Override
    public void moveupTeachPlan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        Long parentid = teachplan.getParentid();
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid,parentid);
        List<Teachplan> teachplanList = teachplanMapper.selectList(queryWrapper);
//        只有一个无法上移
        if(teachplanList.size()>1){
            Optional<Teachplan> max = teachplanList.stream().max(Comparator.comparing(Teachplan::getOrderby));
            Teachplan teachplan1 = max.get();

//            表示最大的是自己
            if(!teachplan.getOrderby().equals(teachplan1.getOrderby())){
                LambdaQueryWrapper<Teachplan> queryWrapper2 = new LambdaQueryWrapper<>() ;
                queryWrapper2.eq(Teachplan::getParentid,parentid).eq(Teachplan::getOrderby,teachplan.getOrderby()+1l);
                Teachplan teachplan2 = teachplanMapper.selectOne(queryWrapper2);
                Integer orderBy = teachplan2.getOrderby();
                teachplan2.setOrderby(teachplan.getOrderby());
                teachplanMapper.updateById(teachplan2);
                teachplan.setOrderby(orderBy);
                teachplanMapper.updateById(teachplan);
            }
        }

    }


    //下移
    @Override
    public void movedownTeachPlan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        Long parentid = teachplan.getParentid();
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid,parentid);
        List<Teachplan> teachplanList = teachplanMapper.selectList(queryWrapper);
//        只有一个无法上移
        if(teachplanList.size()>1){
            Optional<Teachplan> min = teachplanList.stream().min(Comparator.comparing(Teachplan::getOrderby));
            Teachplan teachplan1 = min.get();

//            表示的是自己
            if(!teachplan.getOrderby().equals(teachplan1.getOrderby())){
                LambdaQueryWrapper<Teachplan> queryWrapper2 = new LambdaQueryWrapper<>() ;
                queryWrapper2.eq(Teachplan::getParentid,parentid).eq(Teachplan::getOrderby,teachplan.getOrderby()-1l);
                Teachplan teachplan2 = teachplanMapper.selectOne(queryWrapper2);
                Integer orderBy = teachplan2.getOrderby();
                teachplan2.setOrderby(teachplan.getOrderby());
                teachplanMapper.updateById(teachplan2);
                teachplan.setOrderby(orderBy);
                teachplanMapper.updateById(teachplan);
            }
        }
    }

    @Override
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
//        先删除原有记录
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,bindTeachplanMediaDto.getTeachplanId());
        int delete = teachplanMediaMapper.delete(queryWrapper);

        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia) ;
    }

    @Override
    public Teachplan getTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        return teachplan;
    }

    private int getTeachPalnCount(Long parentid, Long courseId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>() ;
        queryWrapper= queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return (count+1);
    }
}
